const jwt = require('jsonwebtoken');
const config = require('../config');

module.exports = async (ctx, next) => {
  const authHeader = ctx.headers.authorization;
  if (!authHeader) {
    ctx.status = 401;
    ctx.body = { error: 'Authorization header missing' };
    console.error('Authorization header missing');
    return;
  }

  const token = authHeader.split(' ')[1];
  if (!token) {
    ctx.status = 401;
    ctx.body = { error: 'Token missing' };
    return;
  }

  try {
    const decoded = jwt.verify(token, config.jwtSecret);
    ctx.state.user = decoded; // Attach user information to context state
    await next();
  } catch (err) {
    ctx.status = 401;
    ctx.body = { error: 'Invalid token' };
  }
};
